package com.ibeetl.admin.core.web.query;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.annotatoin.ColumnIgnore;
import org.beetl.sql.core.engine.PageQuery;

import javax.persistence.Column;
import java.lang.reflect.Field;

/**
 * 子类继承此类获得翻页功能
 * @author lijiazhi
 */
public class PageParam {
	@ColumnIgnore
	@JsonIgnore
    private Integer page = null;
	@ColumnIgnore
	@JsonIgnore
    private Integer limit = null;
    //排序字段
    @ColumnIgnore
    @JsonIgnore
    private String field;
    //排序方法，asc desc null
    @ColumnIgnore
    @JsonIgnore
    private String order;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }


    @JsonIgnore
    public PageQuery getPageQuery() {
        PageQuery query = new PageQuery();
        query.setParas(this);
        if (page != null) {
            query.setPageNumber(page);
            query.setPageSize(limit);
        }
        if (!StringUtils.isEmpty(order)){
        	//有排序
	        String dbField = null;
	        Class cls = this.getClass();
	        Field f = null;
	        try {
		        f = cls.getDeclaredField(field);
	        } catch (NoSuchFieldException e) {
		        e.printStackTrace();
	        }
	        Column column = f.getAnnotation(Column.class);
	        if (column!=null) {
				dbField = column.name();
	        } else {
		        dbField = field.replaceAll("([A-Z])","_$1");
	        }
			query.setOrderBy(dbField+" "+order);
        }
        return query;
    }

	public Integer getLimit() {
		return limit;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public static void main(String[] args) {
    	String field = "cpId";
    	System.out.println(field.replaceAll("([A-Z])","_$1"));
	}
}
